//循w3c关于WebSocket API的相关规范，浏览器提供了WebSocket类型，在Firefox中为MozWebSocket
window.WebSocket = window.WebSocket || window.MozWebSocket;
//localStorage html新特性用于本地存储数据,比cookie存储空间大很多，此处用来存储聊天记录
var storage = window.sessionStorage;
//发送人
var sendFrom = $("#userId").val();
//接收人
var sendTo = null;
//接收人头像url
var sendToImgUrl = null;
//type [1:发送，2：接收]
$(function(){ 

	
	//建立WebSocket连接
	 var webSocket = new WebSocket("ws://"+ window.location.hostname+":8888/test?userId="+sendFrom);;

	 console.log(window.location.hostname+"connect start");
	 
	 //接收服务器端消息
	 webSocket.onmessage = function(event){ 
	   var data =event.data;
	   console.log(data);
	   var jsonData = null;
	   try{
	   	jsonData = JSON.parse(data);
	   }catch(err){ 
	   	console.log("error:"+err)
	   }
	   
	   //接收在线实时消息
	   if(jsonData.userOnlines != null){
	 	  $("#userOnlines").html("在线人数："+jsonData.userOnlines);
	   }
	   
	   //接收聊天信息
	   if(jsonData.msg != null && jsonData.sendFrom != null){
		   addChatRecords(jsonData.msg,jsonData.sendFrom,sendFrom,2);
		   if(jsonData.sendFrom == sendTo){
			   chat("leftBubble",sendToImgUrl,jsonData.msg);
		   }else{
			   $("#unreadBox"+jsonData.sendFrom).show();
		   }
	   }
	   
	 };
	 
	 //错误处理事件
	 webSocket.onerror = function(event) {
		 console.error(event.data);
	 };
	 
	 //给服务器端发送握手动作
	 webSocket.onopen = function(event){
	 	 var data = event.data;  
	     console.log(data);
	 };

	//关闭
	webSocket.onclose = function(event) {
		 console.log("Web Socket closed.");
	 };

   sendData = function(data){
	 	 webSocket.send(JSON.stringify(data));
	}
	 
	//回车键发送消息
	$(document).keyup(function(event){
		  if(event.keyCode ==13){
		    $("#send-btn").trigger("click");
		  }
    });
	
   $("#send-btn").click(function(){
       //右侧 自己发 调用，只需填一个参数"rightBubble"
       chat("rightBubble",$("#headerImg").val(),$('#sendInfo').val());
       var sendDataInfo = {"msg":$('#sendInfo').val(),"userId":sendFrom,"sendTo":sendTo};
       addChatRecords($('#sendInfo').val(),sendFrom,sendTo,1);
	   sendData(sendDataInfo);
       //清空输入框
       $('#sendInfo').val('');
   })
   
   $(".userItem").on("click",function(){
	   
	   //初始化聊天标题
	   var nickName = $(this).find(".user-box").html();
	   sendToImgUrl = $(this).find("img").attr("src");
	   sendTo = $(this).find("input[name='otherUserId']").val();
	   var msHeaderHtml = '<div class="panel panel-default" style="margin-bottom:0px;height:52px;" >'
	  +'<div class="img-box">'
	   	 + '<img src="'+sendToImgUrl+'"/>'
	   +'</div>'
	   +'<div class="user-box">'
	   +nickName+'</div>'
	   + '<input type="hidden" name="otherUserId" value="'+sendTo+'"/>'
	   + '</div>';
	   $(".im-ms-header").html(msHeaderHtml);
	   
	   //移除未读标识
	   $("#unreadBox"+sendTo).hide();
	   
	   //初始化聊天记录
	   $(".bubbleDiv").html("");
	   var chatRecords = getChatRecords(sendFrom,sendTo);
	   for(var i in chatRecords){
		   if(chatRecords[i].type == 1){
			   chat("rightBubble",$("#headerImg").val(),chatRecords[i].msg);
		   }else{
			   chat("leftBubble",sendToImgUrl,chatRecords[i].msg);
		   }
	   }
   })
   
 
 
 //增加聊天记录
 addChatRecords = function(msg,sendFrom,sendTo,type){
	 var itemKey = null;
	 if(type == 1){
		 itemKey = sendFrom+sendTo;
	 }else{
		 itemKey = sendTo+sendFrom; 
	 }
	 var chatRecordStr = storage.getItem(itemKey);
	 if(chatRecordStr == null){
		 var  chatRecordJson = [];
		 chatRecordJson.push({"userId":sendFrom,"msg":msg,"type":type});
		 storage.setItem(itemKey,JSON.stringify(chatRecordJson));
	 }else{
		 var chatRecordJson  = eval("(" +chatRecordStr+")");
		 chatRecordJson.push({"userId":sendFrom,"msg":msg,"type":type});
		 storage.setItem(itemKey,JSON.stringify(chatRecordJson));
	 }
	 
 }
 
 //获取聊天记录
 getChatRecords = function(sendFrom,sendTo){
	 var chatRecordStr = storage.getItem(sendFrom+sendTo);
	 return  eval("(" +chatRecordStr+")");
 }
   
}); 


